package app;

import java.util.Arrays;

public class App {

    public static void main(String[] args) throws Exception {
        // int[] nums = { 0, 1, 2, 2, 3, 0, 4, 2 };
        int[] nums = { 0, 0, 1, 1, 1, 1, 2, 3, 3,4 };
        // moveZeroes(nums);
        // removeElement(nums, 2);
        removeDuplicates2(nums);
        // removeDuplicates2(nums);
    }

    // 移动零
    public static void moveZeroes(int[] nums) {
        int length = nums.length;
        int tempIndex = 0;
        for (int i = 0; i < length; i++) {
            if (nums[i] != 0) {
                int temp = nums[tempIndex];
                nums[tempIndex] = nums[i];
                nums[i] = temp;
                tempIndex += 1;
            }

        }
        System.out.println(Arrays.toString(nums));
    }

    // 移除元素
    public static int removeElement(int[] nums, int val) {
        int length = nums.length;
        int tempIndex = 0;

        for (int i = 0; i < length; i++) {
            if (nums[i] != val) {
                int temp = nums[tempIndex];
                nums[tempIndex] = nums[i];
                nums[i] = temp;

                tempIndex += 1;
            }

        }
        System.out.println(Arrays.toString(nums));
        System.out.println(tempIndex);
        return tempIndex;
    }

    // 删除排序数组中的重复项
    public static int removeDuplicates(int[] nums) {
        int length = nums.length;
        int tempValue = Integer.MAX_VALUE;
        int k = 0;
        for (int i = 0; i < length; i++) {
            if (nums[i] != tempValue) {
                tempValue = nums[i];
                // System.out.println(tempValue+"===="+nums[k++]);
                nums[k++] = tempValue;
                System.out.println("kkk==" + k);
            }

        }
        System.out.println(Arrays.toString(nums));
        return k;
    }
   //给定一个增序排列数组 nums ，你需要在 原地 删除重复出现的元素，使得每个元素最多出现两次，返回移除后数组的新长度。
    public static int removeDuplicates2(int[] nums) {
        // int[] nums = { 0, 0, 1, 1, 1, 1, 2, 3, 3 ，4};
  
        int length = nums.length;

        int k = 0;
        for (int i = 0; i < length; i++) {
            System.out.println(i+"==="+(k-2));
            //k 特别有用 排重 需要重复几次 这里就减去几
            if (k < 2 || nums[i] != nums[k - 2]) {
                int j=k++;
                nums[j] = nums[i];
            }

        }
        System.out.println(Arrays.toString(nums)+"==="+k);
        return k;
    }
}